<template>
	<view class="task-bg">
		<uv-navbar
			title="任务"
			placeholder
			:auto-back="false"
			bg-color="transparent"
      left-icon=""
			title-style="color: #000000; font-size: 32rpx"
		/>
		<view class="fixbox">
			<map key="map" :show-location="true" :style="{ height: windowHeight + 'px', width: '100%' }"
				:latitude="state.latitude" :longitude="state.longitude" :scale="scale"
				:markers="state.isReloadMap ? state.markers : []" />
			<scroll-view style="height: 56vh" scroll-y :scroll-top="0" @scrolltolower="scrolltolower">
				<view class="list ss-flex ss-row-left ss-r-20 ss-shadow" v-for="(i, index) in dataList" :key="index"
					@click="handleDetail(i.subPlanId, i.projectName, i.cycleNo)">
					<view class="list_l" :style="{
							backgroundColor: getStatusColor(i.status),
							height: i.status == 4 ? '330rpx' : '250rpx',
						}">
					</view>
					<view class="ss-grey-2 ss-w-100 ss-font-24">
						<view class="ss-m-x-20">
							<view class="ss-m-y-14 ss-font-28 ss-black">
								{{ i.projectName }} ( 第{{ i.cycleNo }}期 ）
							</view>
							<view class="ss-m-y-10 ss-flex">
								{{ i.beginTime }}
								<view class="mes ss-m-x-20">{{ i.remark }}</view>
							</view>
							<view class="ss-m-y-14 ss-flex">
								总体：
								<uv-line-progress :percentage="i.projectRate" :activeColor="getStatusColor(i.status)" />
							</view>
							<view class="ss-m-y-14 ss-flex">
								本月：
								<uv-line-progress :percentage="i.subPlantRate"
									:activeColor="getStatusColor(i.status)" />
							</view>
							<view class="ss-m-y-14">
								<uv-icon :name="getStatusIcon(i.status)" :label="getStatusLabel(i.status)" size="16"
									labelSize="12" />
							</view>
						</view>
						<view class="list_line ss-font-26" v-if="i.status == 4 && i.projectLeader" @tap.stop="toReport(i.subPlanId)">
							生成报告
						</view>
					</view>
				</view>
				<uv-load-more v-if="dataList.length > 0" :status="status" line />
				<uv-empty v-else margin-top="20vh" :icon="empty" text="暂无任务" />
			</scroll-view>
		</view>
	</view>
</template>
<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed,
		nextTick,
		watch,
		onBeforeUnmount
	} from "vue";
	import {
		taskList,
		generateReport
	} from "@/request/task.js";
	import empty from "@/static/empty.png";
	import iconGreen from "@/static/sign/green.png";
	import iconRed from "@/static/sign/red.png";
	import iconClock from "@/static/home/icon_clock.png";
	import iconSuccess from "@/static/home/icon_success.png";
	import iconProgress from "@/static/home/icon_progress.png";
	import iconWarn from "@/static/home/icon_warn.png";

	const props = defineProps({
		// 是否下拉刷新
		refresh: {
			type: Boolean,
			default: false,
		},
		// 上拉加载
		onMore: {
			type: Boolean,
			default: false,
		},
	});

	const emit = defineEmits(["update:refresh", "update:onMore", "count"]);

	const total = ref(0); // 总条数
	const includePoints = ref([]);
	const queryParams = reactive({
		pageNum: 1, // 页码
		pageSize: 10, // 条数
	});
	const dataList = ref([]); // 数据列表
	const status = ref("loadmore"); // 加载状态
	const state = reactive({
		latitude: 30.65284, // 纬度
		longitude: 104.066133, // 经度
		markers: [], // 地图标记列表
		isReloadMap: true, // 是否刷新地图
	});

	// 获取高度
	const windowHeight = computed(() => {
		var systemInfo = uni.getSystemInfoSync();
		return systemInfo.windowHeight / 3.8;
	});

	// 获取高度
	const scale = computed(() => {
		let obj = {
			centralPoint: [state.latitude, state.longitude],
			otherPoint: includePoints.value,
		};
		return furthest(obj);
	});

	const getGreatCircle = (coordinate1, coordinate2) => {
		var lat1 = coordinate1[0]; // 纬度
		var lat2 = coordinate2[0];
		var lng1 = coordinate1[1]; // 经度
		var lng2 = coordinate2[1];

		var radLat1 = getRad(lat1);
		var radLat2 = getRad(lat2);

		var a = radLat1 - radLat2;
		var b = getRad(lng1) - getRad(lng2);

		var s =
			2 *
			Math.asin(
				Math.sqrt(
					Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
				)
			);
		var EARTH_RADIUS = 6378137.0;
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000.0;

		return s;
	};

	const getRad = (d) => {
		var EARTH_RADIUS = 6378137.0; //单位M
		var PI = Math.PI;
		return (d * PI) / 180.0;
	};

	const furthest = (obj) => {
		// obj包含中心点坐标和其他所有的坐标位置  处理obj传入的参数
		let centralPoint = obj.centralPoint; // 中心点
		let otherPoint = obj.otherPoint; // 二维数组存放其他坐标点

		// 循环遍历得出距离最远的1个坐标然后*2
		let farthestCoordinate = []; // 当前最远坐标
		let farthestDistance = 0; // 最远距离
		let dis = null; // 存储当前距离

		for (let i in otherPoint) {
			let newLocation = [];
			newLocation[0] = otherPoint[i].latitude;
			newLocation[1] = otherPoint[i].longitude;

			dis = getGreatCircle(centralPoint, newLocation);
			if (dis > farthestDistance) {
				farthestDistance = dis;
				farthestCoordinate = newLocation;
			}
		}

		farthestDistance = farthestDistance / 1000; // 转为km

		// 根据坐标计算出合理的比例尺寸
		let surface = [500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02];

		for (let i in surface) {
			if (farthestDistance > surface[i]) {
				let scale = 5 + Number(i);
				return scale;
			}
		}
		return 16;
	};

	watch(
		props,
		(v) => {
			if (v?.refresh) {
				setTimeout(() => {
					queryParams.pageNum = 1;
					getList();
				}, 0);
			}
			if (v?.onMore) {
				if (total.value > dataList.value.length) {
					queryParams.pageNum += 1;
					getList();
				}
			}
		}, {
			immediate: true,
			deep: true,
		}
	);

	onMounted(() => {
		getLocationInfo();
		getList();
		uni.$on("taskReport", () => {
			getList();
		});
		uni.$on("listStateTask", () => {
			getList();
		});
		// #ifdef APP-PLUS
		// 禁止下拉刷新
		const pages = getCurrentPages();  
		const page = pages[pages.length - 1];  
		const currentWebview = page.$getAppWebview();
		currentWebview.setStyle({  
			pullToRefresh: {  
				support: false,
				style: plus.os.name === 'Android' ? 'circle' : 'default'
			}  
		});
		// #endif
	});

	onBeforeUnmount(() => {
		uni.$off("taskReport");
		uni.$off("listStateTask");
	});

	// 刷新地图
	const reloadMap = () => {
		state.isReloadMap = false;
		nextTick(() => {
			state.isReloadMap = true;
		});
	};

	// 获取图标文字
	const getStatusLabel = (e) => {
		switch (e) {
			case 2:
				return "未开始";
			case 3:
				return "进行中";
			case 4:
				return "已完成";
			case 5:
				return "已超时";
			default:
				return "";
		}
	};

	// 获取图标样式
	const getStatusIcon = (e) => {
		switch (e) {
			case 2:
				return iconClock;
			case 3:
				return iconProgress;
			case 4:
				return iconSuccess;
			case 5:
				return iconWarn;
			default:
				return "";
		}
	};

	// 获取图标颜色
	const getStatusColor = (e) => {
		switch (e) {
			case 2:
				return "#F2CE90";
			case 3:
				return "#87BCF5";
			case 4:
				return "#85C889";
			case 5:
				return "#F2AFA5";
			default:
				return "";
		}
	};

	// 获取当前定位
	const getLocationInfo = () => {
		uni.getLocation({
			type: "gcj02",
			success: async (res) => {
				console.log("坐标：", res);
				state.latitude = res.latitude;
				state.longitude = res.longitude;
				await getList();
				reloadMap();
				console.log("当前位置的经度：" + res.longitude);
				console.log("当前位置的纬度：" + res.latitude);
			},
			fail: (e) => {
				console.log("获取位置失败：", e);
				setTimeout(() => {
					getLocationInfo();
				}, 1000);
			}
		});
	};

	const scrolltolower = () => {
		if (total.value > dataList.value.length) {
			queryParams.pageNum += 1;
			getList();
		}
	}

	// 获取任务列表
	const getList = () => {
		status.value = "loading";
		taskList(queryParams)
			.then((res) => {
				if (res.code == 200) {
					dataList.value =
						queryParams.pageNum == 1 ? res.rows : dataList.value.concat(res.rows);
					total.value = res.total;
					// 获取地图标记列表
					if (dataList.value.length == 0) {
						state.markers = [{
							id: 1,
							latitude: state.latitude || 0,
							longitude: state.longitude || 0,
							title: "",
							iconPath: iconGreen,
							width: 24,
							height: 27,
						}, ];
					} else {
						state.markers = dataList.value.map((item, index) => {
							return {
								id: index,
								latitude: parseFloat(item.latitude) || 0,
								longitude: parseFloat(item.longitude) || 0,
								title: item.projectName,
								iconPath: iconRed,
								width: 24,
								height: 27,
							};
						});

						state.markers.unshift({
							id: -1,
							latitude: state.latitude || 0,
							longitude: state.longitude || 0,
							title: "",
							iconPath: iconGreen,
							width: 24,
							height: 27,
						});
					}

					includePoints.value = state.markers.map((item) => {
						return {
							latitude: item.latitude,
							longitude: item.longitude,
						};
					});

					reloadMap();
					console.log(state.markers, " state.markers", includePoints.value);
				}
			})
			.finally(() => {
				emit("update:refresh", false);
				uni.stopPullDownRefresh();
				status.value = total.value == dataList.value.length ? "nomore" : "loadmore";
				if (props?.onMore) emit("update:onMore", false);
			});
	};

	// 跳转任务选择
	const handleDetail = (id, projectName, cycleNo) => {
		uni.navigateTo({
			url: `/pages/Task/select?subPlanId=${id}&projectName=${projectName}&cycleNo=${cycleNo}`,
		});
	};

	// 生成报告
	const toReport = (id) => {
		generateReport(id).then((res) => {
			if (res.code == 200) {
				uni.navigateTo({
					url: "/pages/Task/reportDetails?id=" + res.data,
				});
			}
		});
	};
</script>
<style lang="scss" scoped>
	@import "@/uni.scss";
	.task-bg {
		width: 100vw;
		height: 100vh;
		background: url("@/static/taskBg.png") no-repeat 100% 100%;
	}

	.fixbox {
		background-color: #ffffff;
		padding: 8rpx;
		margin: 0 auto;
		width: 92.2vw;
		height: calc(100vh - var(--status-bar-height) - 260rpx);
		box-sizing: border-box;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.list {
		width: 90%;
		margin: 30rpx auto;
		overflow: hidden;

		.list_l {
			width: 22rpx;
			background: #87bcf5;
			height: 330rpx;
		}

		.mes {
			color: red;
		}

		.list_line {
			border-top: 2rpx solid gainsboro;
			padding-top: 14rpx;
			width: 100%;
			text-align: center;
		}
	}

	.amap-icon {
		overflow: inherit !important;
	}
</style>